package com.ruoyi.cms.controller.my;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ruoyi.cms.domain.CmsArticle;
import com.ruoyi.cms.domain.CmsOrder;
import com.ruoyi.cms.domain.CmsOrderMessage;
import com.ruoyi.cms.service.ICmsArticleService;
import com.ruoyi.cms.service.ICmsOrderMessageService;
import com.ruoyi.cms.service.ICmsOrderService;
import com.ruoyi.common.config.AlipayConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/cmsApp/article")
public class CmsAppArticleController extends BaseController {

    @Autowired
    private ICmsArticleService cmsArticleService;

    @Autowired
    ICmsOrderService cmsOrderService;

    @Autowired
    private ICmsOrderMessageService cmsOrderMessageService;

    @GetMapping("/getVersion")
    public R getVersion(){
        return R.ok(2);
    }

    @GetMapping("/articleTitleLike")
    public R articleTitleLike(String keyword){
        return R.ok();
    }

    @GetMapping("/list")
    public TableDataInfo list(CmsArticle cmsArticle)
    {
        startPage();
        List<CmsArticle> list = cmsArticleService.selectCmsArticleList(cmsArticle);
        return getDataTable(list);
    }

    @GetMapping("/listCode")
    public TableDataInfo listCode(CmsArticle cmsArticle)
    {
        startPage();
        List<CmsArticle> list = cmsArticleService.selectCmsArticleCodeList(cmsArticle);
        return getDataTable(list);
    }


    @Autowired
    AlipayConfig alipayConfig;

    @PostMapping("/wapPay")
    public R wapPay(@RequestBody JSONObject jsonObject) throws AlipayApiException {

        int amount = jsonObject.getInteger("amount");
        Long articleId = jsonObject.getLong("articleId");

        CmsArticle cmsArticle = cmsArticleService.selectCmsArticleById(articleId);
        if(cmsArticle == null){
            return R.fail("请刷新页面");
        }

        Long userId = SecurityUtils.getUserId();
        CmsOrder cmsOrder = new CmsOrder();
        cmsOrder.setUserId(userId);
        cmsOrder.setArticleId(articleId);
        cmsOrder.setAmount(amount);
        cmsOrder.setCreateTime(new Date());
        cmsOrder.setOrderStatus(1);
        cmsOrder.setCreateBy(SecurityUtils.getUsername());
        cmsOrderService.insertCmsOrder(cmsOrder);


        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(),alipayConfig.getAppId(),alipayConfig.getAppPrivateKey(),
                alipayConfig.getFormat(),alipayConfig.getCharset(),alipayConfig.getAlipayPublicKey(),alipayConfig.getSignType());

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl()); // 异步通知地址

        // 构造业务参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", IdUtils.fastSimpleUUID());
        bizContent.put("total_amount", amount);
        bizContent.put("subject", "打赏");
        bizContent.put("product_code", "QUICK_WAP_WAY");
        bizContent.put("passback_params", "orderId="+cmsOrder.getId()+"&userId="+userId+"&articleTitle="+cmsArticle.getTitle()
                +"&shareUrl="+cmsArticle.getShareUrl()+"&shareCode="+cmsArticle.getShareCode());

        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");

        System.out.println(response.getBody());
        return R.ok(response.getBody());
    }

    @PostMapping("/createOrder")
    public R createOrder(@RequestBody JSONObject jsonObject) throws AlipayApiException {
        int amount = jsonObject.getInteger("amount");
        Long articleId = jsonObject.getLong("articleId");
        CmsOrder cmsOrder = new CmsOrder();
        cmsOrder.setUserId(SecurityUtils.getUserId());
        cmsOrder.setArticleId(articleId);
        cmsOrder.setAmount(amount);
        cmsOrder.setCreateTime(new Date());
        cmsOrder.setOrderStatus(1);
        cmsOrder.setCreateBy(SecurityUtils.getUsername());
        cmsOrderService.insertCmsOrder(cmsOrder);
        return R.ok();
    }

    @PostMapping("/createAlipayOrder")
    public R createAlipayOrder(@RequestBody JSONObject jsonObject) throws AlipayApiException {
        int amount = jsonObject.getInteger("amount");
        Long articleId = jsonObject.getLong("articleId");
        CmsOrder cmsOrder = new CmsOrder();
        cmsOrder.setUserId(SecurityUtils.getUserId());
        cmsOrder.setArticleId(articleId);
        cmsOrder.setAmount(amount);
        cmsOrder.setCreateTime(new Date());
        cmsOrder.setOrderStatus(1);
        cmsOrder.setCreateBy(SecurityUtils.getUsername());
        cmsOrderService.insertCmsOrder(cmsOrder);


        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(),alipayConfig.getAppId(),alipayConfig.getAppPrivateKey(),
                alipayConfig.getFormat(),alipayConfig.getCharset(),alipayConfig.getAlipayPublicKey(),alipayConfig.getSignType());

        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl("https://your-domain.com/notify"); // 异步通知地址

        // 构造业务参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", IdUtils.fastSimpleUUID());
        bizContent.put("total_amount", amount);
        bizContent.put("subject", "打赏");
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);

        return R.ok(response.getBody());
    }

    @GetMapping("/messageList")
    public TableDataInfo list(CmsOrderMessage cmsOrderMessage)
    {
        cmsOrderMessage.setUserId(SecurityUtils.getUserId());
        startPage();
        List<CmsOrderMessage> list = cmsOrderMessageService.selectCmsOrderMessageList(cmsOrderMessage);
        return getDataTable(list);
    }


}
